<template>
  <div class="p-2" id="attendance-stats-view">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="58px" class="search-form">
          <el-form-item label="宿舍楼" prop="buildingId"> <BuildingSelect v-model="queryParams.buildingId" /> </el-form-item>
          <el-form-item label="考勤组" prop="groupId">
            <!-- <el-input v-model="queryParams.groupId" placeholder="请输入宿舍楼ID" clearable style="width: 240px" @keyup.enter="handleQuery" /> -->
            <el-tree-select
              style="width: 240px"
              v-model="queryParams.groupId"
              :data="formGroupOptions"
              :props="{ value: 'id', label: 'label', children: 'children' }"
              value-key="deptId"
              placeholder="请选择考勤分组"
              check-strictly
            />
          </el-form-item>
          <!-- <el-form-item label="总人数" prop="roomMemberCount">
            <el-input v-model="queryParams.roomMemberCount" placeholder="请输入总人数" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="请假人数" prop="leaveApplyCount">
            <el-input v-model="queryParams.leaveApplyCount" placeholder="请输入请假人数" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="考勤数据" prop="snapshoot">
            <el-input v-model="queryParams.snapshoot" placeholder="请输入考勤数据" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item label="时间" style="width: 308px">
            <el-date-picker
              v-model="dateRangeAttendanceDate"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            />
          </el-form-item>
          <el-form-item>
            <el-button-group>
              <el-button @click="timeClick(1)">当天考勤</el-button>
              <el-button @click="timeClick(2)">本周</el-button>
              <el-button @click="timeClick(3)">本月</el-button>
            </el-button-group>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!-- <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['dormitory:attendanceStats:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['dormitory:attendanceStats:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              v-hasPermi="['dormitory:attendanceStats:remove']"
              >删除</el-button
            >
          </el-col> -->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['dormitory:attendanceStats:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table height="calc(100vh - 300px)" stripe v-loading="loading" :data="attendanceStatsList" @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <!-- <el-table-column label="ID" align="center" prop="id" v-if="true" /> -->
        <el-table-column label="宿舍楼" align="center" prop="buildingName" />
        <el-table-column label="楼层" align="center" prop="floorCount">
          <template #default="scope">
            <span>{{scope.row.floorCount+'层' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="总人数" align="center" prop="memberCount" />
        <!-- <el-table-column label="考勤数据" align="center" prop="snapshoot" /> -->
        <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
        <el-table-column label="日期" align="center" prop="createTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.attendanceDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="早上出寝" align="left" prop="attendanceShift1" width="120">
          <template #default="scope">
            <div v-if="scope.row.attendanceShift1" class="attendanceShift">
              <p @click="handleDetailList(scope.row,1,1)">{{ "正常："+scope.row.attendanceShift1.normalCount }}</p>
              <p @click="handleDetailList(scope.row,1,2)">{{ "晚打卡："+scope.row.attendanceShift1.exceptionCount }}</p>
              <p @click="handleDetailList(scope.row,1,3)">{{ "缺卡："+scope.row.attendanceShift1.missingCount }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="中午入寝" align="left" prop="attendanceShift2" width="120">
          <template #default="scope">
            <div v-if="scope.row.attendanceShift2" class="attendanceShift">
              <p @click="handleDetailList(scope.row,2,1)">{{ "正常："+scope.row.attendanceShift2.normalCount }}</p>
              <p @click="handleDetailList(scope.row,2,2)">{{ "晚打卡："+scope.row.attendanceShift2.exceptionCount }}</p>
              <p @click="handleDetailList(scope.row,2,3)">{{ "缺卡："+scope.row.attendanceShift2.missingCount }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="中午出寝" align="left" prop="attendanceShift3" width="120">
          <template #default="scope">
            <div v-if="scope.row.attendanceShift3" class="attendanceShift">
              <p @click="handleDetailList(scope.row,3,1)">{{ "正常："+scope.row.attendanceShift3.normalCount }}</p>
              <p @click="handleDetailList(scope.row,3,2)">{{ "晚打卡："+scope.row.attendanceShift3.exceptionCount }}</p>
              <p @click="handleDetailList(scope.row,3,3)">{{ "缺卡："+scope.row.attendanceShift3.missingCount }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="下午入寝" align="left" prop="attendanceShift4" width="120">
          <template #default="scope">
            <div v-if="scope.row.attendanceShift4" class="attendanceShift">
              <p @click="handleDetailList(scope.row,4,1)">{{ "正常："+scope.row.attendanceShift4.normalCount }}</p>
              <p @click="handleDetailList(scope.row,4,2)">{{ "晚打卡："+scope.row.attendanceShift4.exceptionCount }}</p>
              <p @click="handleDetailList(scope.row,4,3)">{{ "缺卡："+scope.row.attendanceShift4.missingCount }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="下午出寝" align="left" prop="attendanceShift5" width="120">
          <template #default="scope">
            <div v-if="scope.row.attendanceShift5" class="attendanceShift">
              <p @click="handleDetailList(scope.row,5,1)">{{ "正常："+scope.row.attendanceShift5.normalCount }}</p>
              <p @click="handleDetailList(scope.row,5,2)">{{ "晚打卡："+scope.row.attendanceShift5.exceptionCount }}</p>
              <p @click="handleDetailList(scope.row,5,3)">{{ "缺卡："+scope.row.attendanceShift5.missingCount }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="晚上出入寝" align="left" prop="attendanceShift6" width="120">
          <template #default="scope">
            <div v-if="scope.row.attendanceShift6" class="attendanceShift">
              <p @click="handleDetailList(scope.row,6,1)">{{ "正常："+scope.row.attendanceShift6.normalCount }}</p>
              <p @click="handleDetailList(scope.row,6,2)">{{ "晚打卡："+scope.row.attendanceShift6.exceptionCount }}</p>
              <p @click="handleDetailList(scope.row,6,3)">{{ "缺卡："+scope.row.attendanceShift6.missingCount }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="请假人数" align="left" prop="leaveApplyCount">
          <template #default="scope">
            <div class="attendanceShift">
              <p>{{ scope.row.leaveApplyCount }}</p>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['dormitory:attendanceStats:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['dormitory:attendanceStats:remove']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column> -->
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改宿舍考勤统计对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="attendanceStatsFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="宿舍楼ID" prop="buildingId">
          <el-input v-model="form.buildingId" placeholder="请输入宿舍楼ID" />
        </el-form-item>
        <el-form-item label="总人数" prop="roomMemberCount">
          <el-input v-model="form.roomMemberCount" placeholder="请输入总人数" />
        </el-form-item>
        <el-form-item label="请假人数" prop="leaveApplyCount">
          <el-input v-model="form.leaveApplyCount" placeholder="请输入请假人数" />
        </el-form-item>
        <el-form-item label="考勤数据" prop="snapshoot">
          <el-input v-model="form.snapshoot" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <AttendanceDetailDialog ref="attendanceDetailDialogRef" />
  </div>
</template>

<script setup name="AttendanceStats" lang="ts">
import {
  listAttendanceStats,
  getAttendanceStats,
  delAttendanceStats,
  addAttendanceStats,
  updateAttendanceStats
} from '@/api/dormitory/attendanceStats';
import { AttendanceStatsVO, AttendanceStatsQuery, AttendanceStatsForm } from '@/api/dormitory/attendanceStats/types';
import AttendanceDetailDialog from './modules/AttendanceDetailDialog.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const attendanceStatsList = ref<AttendanceStatsVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRangeAttendanceDate = ref<[DateModelType, DateModelType]>(['', '']);
const attendanceDetailDialogRef = ref<InstanceType<typeof AttendanceDetailDialog>>();

const queryFormRef = ref<ElFormInstance>();
const attendanceStatsFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: AttendanceStatsForm = {
  id: undefined,
  buildingId: undefined,
  roomMemberCount: undefined,
  leaveApplyCount: undefined,
  snapshoot: undefined,
  remark: undefined
};
const data = reactive<PageData<AttendanceStatsForm, AttendanceStatsQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    buildingId: undefined,
    roomMemberCount: undefined,
    leaveApplyCount: undefined,
    snapshoot: undefined,
    params: {
      createTime: undefined
    }
  },
  rules: {
    id: [{ required: true, message: 'ID不能为空', trigger: 'blur' }],
    buildingId: [{ required: true, message: '宿舍楼ID不能为空', trigger: 'blur' }],
    roomMemberCount: [{ required: true, message: '总人数不能为空', trigger: 'blur' }],
    leaveApplyCount: [{ required: true, message: '请假人数不能为空', trigger: 'blur' }],
    snapshoot: [{ required: true, message: '考勤数据不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

import { groupTreeSelect } from '@/api/attendance/setting/group';
const formGroupOptions = ref<any[]>([]);

const loagGroupTree = async () => {
  const res = await groupTreeSelect({ groupType: 3 });
  formGroupOptions.value = res.data;
};

/** 查询宿舍考勤统计列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {};
  proxy?.addDateRange(queryParams.value, dateRangeAttendanceDate.value, 'AttendanceDate');
  const res = await listAttendanceStats(queryParams.value);
  for (let row of res.rows) {
    for (let item of JSON.parse(row.snapshoot)) {
      row[`attendanceShift${item.attendanceShift}`] = item;
    }
  }
  attendanceStatsList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  attendanceStatsFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRangeAttendanceDate.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: AttendanceStatsVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加宿舍考勤统计';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: AttendanceStatsVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getAttendanceStats(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改宿舍考勤统计';
};

/** 提交按钮 */
const submitForm = () => {
  attendanceStatsFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateAttendanceStats(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addAttendanceStats(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('修改成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: AttendanceStatsVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除宿舍考勤统计编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delAttendanceStats(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'dormitory/attendanceStats/export',
    {
      ...queryParams.value
    },
    `attendanceStats_${new Date().getTime()}.xlsx`
  );
};

const handleDetailList = (row?: AttendanceStatsVO, attendanceShift: number, validatndResult: number) => {
  attendanceDetailDialogRef?.value.handleShow(row, attendanceShift, validatndResult, queryParams.value.groupId);
};

const timeClick = (type: number) => {
  let startTime = new Date();
  let endTime = new Date();
  if (type == -1) {
    startTime.setDate(startTime.getDate() - 1);
  } else if (type == 2) {
    const days = [0, 1, 2, 3, 4, 5, 6];
    const dayOfWeek = days[startTime.getDay()];
    startTime.setDate(startTime.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1));
  } else if (type == 3) {
    startTime.setDate(1);
  }
  dateRangeAttendanceDate.value = [proxy?.parseTime(startTime, '{y}-{m}-{d}') + ' 00:00:00', proxy?.parseTime(endTime, '{y}-{m}-{d}') + ' 23:59:59'];
};

onMounted(() => {
  timeClick(-1);
  getList();
  loagGroupTree();
});
</script>

<style lang="scss" scoped>
.attendanceShift {
  p {
    padding: 0;
    margin: 0;
    font-size: 13px;
    line-height: 20px;
    color: #2d8cf0;
    cursor: pointer;
    // border-bottom: 1px solid #fff;
    &:hover {
      text-decoration: underline;
    }
  }
}
</style>
